import 'package:basic_common/common_exports.dart';
import 'package:basic_common/time_tool.dart';
import 'package:basic_modle/duty_data.dart';
import 'package:basic_modle/upload_data.dart';
import 'package:basic_widgets/bottom_img_picker.dart';
import 'data/department_data_list.dart';
import 'data/hospital_data_list.dart';
import 'data/idcard_valid_data.dart';

class RealNameController extends GetxController {
  List<String> titles = ["实名认证", "医生身份认证", "资质认证", "完成"];
  TextEditingController nameController = TextEditingController();
  TextEditingController nickNameController = TextEditingController();

  TextEditingController idCardController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController fieldController = TextEditingController(); //擅长领域
  TextEditingController personalController = TextEditingController(); //个人简介
  // 身份证输入框 焦点
  FocusNode focusNode = FocusNode();

// 医护类型
  List careTypeList = ["医生", "护士"];
  List careIdList = <int>[1, 2];

  final hospitalList = <String>[].obs;
  final allHospitalList = <HospitalData>[].obs;
  final hospitalIdList = <String>[].obs;

  final departmentList = <String>[].obs;
  final allDepartmentList = <DepartmentDataList>[].obs;
  final deptIdList = <String>[].obs;

  /// 职务
  final dutyList = <String>[].obs;
  final allDutyList = <DutyData>[].obs;
  final dutyIdList = <String>[].obs;

  /// 职称
  final drTitleList = <String>[].obs;
  final allTitleList = <DutyData>[].obs;
  final drTitleIdList = <String>[].obs;

  final selectCare = '请选择您的医护类型'.obs;
  final selectCarelId = 0.obs; //选择的医院ID

  final selectHospital = '请选择您所在的医院'.obs;
  final selectHospitalId = '-100'.obs; //选择的医院ID

  final selectDepart = '请选择您的科室'.obs;
  final selectDepartId = '-100'.obs; //选择的科室ID

  final selectDuty = '请选择您的职称'.obs;
  final selectDutyId = '-100'.obs; //选择的职务ID

  final selectTitle = '请选择您的职务'.obs;
  final selectTitleId = '-100'.obs; //选择的职称ID

  final imgPath1 = ''.obs; //身份认证 正面
  final imgPath2 = ''.obs; //身份认证 返面

  final imgPathPrac1 = ''.obs; //执业证书 主页
  final imgPathPrac2 = ''.obs; //执业证书 变更页

  final imgPathTitle1 = ''.obs; //职称证书主页
  final imgPathTitle2 = ''.obs; //职称证书变更页

  final imgPathXp = ''.obs; //工作胸牌

  //实名认证按钮是否可用
  final isDisableReal = false.obs;

  //当前进行到哪一步了
  final currentStep = 0.obs;
  String? userId;
  final phoneNum = ''.obs;
  final sex = ''.obs;
  //出生年月
  final birthday = '请输入您的出生年月'.obs;

  final selectKeshi = <String>[].obs;

  final keshiMaps = Map<String, List<dynamic>>().obs;
  Map<String, List<dynamic>> lastList = Map<String, List<dynamic>>().obs;
  final selectKeList = <dynamic>[].obs;
  List<dynamic> allKeshiDataList = [].obs; //科室全部数据
  final selectKeshiNameList = <dynamic>[].obs; // 选中的科室名字
  final selectKeshiIdList = <dynamic>[].obs; // 选中的科室Id

  List<dynamic> allKeshiList = [].obs; //科室显示列表数据
  final address = ''.obs;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    userId = Get.arguments['id'];
    phoneNum.value = Get.arguments['phone'];
    nickNameController.text = nameController.text;
    focusNode.addListener(() {
      if (!focusNode.hasFocus) {
        validId();
      }
    });
    getHospitalList();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    focusNode.dispose();
  }

  /// 新增医生-实名认证
  void addDrRealNAme() async {
    if (userId!.isEmpty) {
      return ToastUtils.toast("医生ID不能为空");
    }
    String name = nameController.text;
    String idCard = idCardController.text;
    String gender = sex.value;
    String birth = birthday.value;
    String email = emailController.text;
    String idImg = imgPath1.value;
    String idImg2 = imgPath2.value;
    String adr = address.value;
    if (name.isEmpty || idCard.isEmpty || gender == -1 || birth.isEmpty) {
      ToastUtils.toast("信息不全，请补充完整");
      isDisableReal.value = false;
      return;
    }
    HttpData res = await ApiService().drRealName(data: {
      "userId": userId,
      "realName": name,
      "idcardNo": idCard,
      "gender": gender,
      "birthday": birth,
      "phone": phoneNum.value,
      "address": adr,
      // "nation": "汉族",
      // "issue": "郑州",
      // "email": email,
      "photo01": idImg,
      "photo02": idImg2,
    });
    if (res.code == 1) {
      nextStep();
    } else {
      ToastUtils.toast("身份认证失败${res.msg}");
    }
  }

  /// 选择图片弹窗
  /// type 上传图片类型
  ///  1 身份证正面 2 身份证反面
  /// 3 执业证书主页 4 执业证书变更页
  /// 5 职称证书主页 6 职称证书变更页
  /// 7 工作胸牌
  showSelectImg({required int type}) {
    BottomImagePickerTool.showBottomSheet(
        onCamera: () => getCameraImgs(userId!, type),
        onGallery: () => getImgs(userId!, type));
  }

  /// 相机拍照
  getCameraImgs(String userId, int type) async {
    XFile? _image;
    final picker = ImagePicker();
    _image = await picker.pickImage(source: ImageSource.camera);
    if (type == 1) {
      imgPath1.value = await uploadSingleFile(_image!.path, userId);
    } else if (type == 2) {
      imgPath2.value = await uploadSingleFile(_image!.path, userId);
    } else if (type == 3) {
      imgPathPrac1.value = await uploadSingleFile(_image!.path, userId);
    } else if (type == 4) {
      imgPathPrac2.value = await uploadSingleFile(_image!.path, userId);
    } else if (type == 5) {
      imgPathTitle1.value = await uploadSingleFile(_image!.path, userId);
    } else if (type == 6) {
      imgPathTitle2.value = await uploadSingleFile(_image!.path, userId);
    } else if (type == 7) {
      imgPathXp.value = await uploadSingleFile(_image!.path, userId);
    }
  }

  /// 选择相册图片
  getImgs(String userId, int type) async {
    XFile? _image;
    final picker = ImagePicker();
    _image = await picker.pickImage(source: ImageSource.gallery);
    if (type == 1) {
      imgPath1.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath1']);
    } else if (type == 2) {
      imgPath2.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath2']);
    } else if (type == 3) {
      imgPathPrac1.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath3']);
    } else if (type == 4) {
      imgPathPrac2.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath4']);
    } else if (type == 5) {
      imgPathTitle1.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath5']);
    } else if (type == 6) {
      imgPathTitle2.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath6']);
    } else if (type == 7) {
      imgPathXp.value = await uploadSingleFile(_image!.path, userId);
      update(['imgPath7']);
    }
  }

  /// 单个图片上传
  Future<String> uploadSingleFile(String path, String userId) async {
    UploadData res = await ApiService().uploadSingle(params: {
      "file": await MultipartFile.fromFile(path),
      "domain": 'fw/${userId}'
    });
    if (res.errCode == 0) {
      return res.uri!;
    }
    return '';
  }

//上一步
  void preStep() {
    if (currentStep.value == 0) {
      return;
    }
    currentStep.value -= 1;
  }

  // 下一步
  void nextStep() {
    if (currentStep.value == 3) {
      return;
    }
    currentStep.value += 1;
  }

  /// 检车提交医生身份信息按钮是否可用
  bool checkBtnStatus() {
    if (selectCare.value == '请选择您的医护类型' ||
        selectHospital.value == '请选择您所在的医院' ||
        selectDepart.value == '请选择您的科室' ||
        selectDuty.value == '请选择您的职务' ||
        selectTitle.value == '请选择您的职称') {
      return false;
    } else {
      return true;
    }
  }

  /// 选择所在医院
  getHospitalList() async {
    hospitalList.clear();
    allHospitalList.clear();
    hospitalIdList.clear();
    HttpData httpdata = await ApiService().getHospitalList();
    if (httpdata.code == 1) {
      List<dynamic> list = httpdata.data;
      for (dynamic itemData in list) {
        HospitalData hosData = HospitalData.fromJson(itemData);
        hospitalList.add(hosData.hospName!);
        allHospitalList.add(hosData);
        hospitalIdList.add(hosData.hospNo!);
      }
      update(['hospList']);
    }
  }

  getDepartmentList() async {
    String hosNo = selectHospitalId.value;
    HttpData httpdata =
        await ApiService().getDepartmentList(data: {"hospNo": hosNo});
    if (httpdata.code == 1) {
      List<dynamic> list = httpdata.data;
      for (dynamic itemData in list) {
        final keshiMaps2 = Map<String, List<dynamic>>().obs;
        DepartmentDataList depData = DepartmentDataList.fromJson(itemData);
        allDepartmentList.add(depData);
        departmentList.add(depData.departmentName!);
        deptIdList.add(depData.departmentNo!);

        keshiMaps2.putIfAbsent(
            depData.departmentName!,
            () => list
                .where((element) => element['parentId'] == depData.id)
                .toList()
                .asMap()
                .entries
                .map((e) => e.value['departmentName'])
                .toList());

        allKeshiList.add(keshiMaps2);
        allKeshiDataList.addAll(list);
      }

      update(['hospList']);
    }
  }

  /// 职务、职称 type doctor_duty   职务 doctor_title 职称
  getDutyList({required String type}) async {
    if (type == "doctor_duty") {
      allDutyList.clear();
      dutyList.clear();
      dutyIdList.clear();
    } else {
      allTitleList.clear();
      drTitleList.clear();
      drTitleIdList.clear();
    }
    HttpData httpdata =
        await ApiService().getDutyList(data: {"dictType": type});
    if (httpdata.code == 1) {
      List<dynamic> list = httpdata.data;
      for (dynamic itemData in list) {
        DutyData dutyData = DutyData.fromJson(itemData);
        if (type == "doctor_duty") {
          //职务
          allDutyList.add(dutyData);
          dutyList.add(dutyData.dictLabel!);
          dutyIdList.add(dutyData.dictValue!);
        } else {
          allTitleList.add(dutyData);
          drTitleList.add(dutyData.dictLabel!);
          drTitleIdList.add(dutyData.dictValue!);
        }
      }
      update(['hospList']);
    }
  }

  /// 提交医生身份信息
  void addDrInfo() async {
    String hospId = selectHospitalId.value;
    int doType = selectCarelId.value;
    String depId = selectDepartId.value;
    String title = selectTitleId.value;
    String duty = selectDutyId.value;
    String nick = nickNameController.text;
    if (hospId.isEmpty ||
        doType == 0 ||
        depId.isEmpty ||
        title.isEmpty ||
        nick.isEmpty ||
        duty.isEmpty ||
        selectKeshiIdList.isEmpty) {
      ToastUtils.toast("数据不全，请重新选择");
      return;
    }
    String depParent = selectKeshiIdList[0];
    String deptChild = selectKeshiIdList[1];
    HttpData httpData = await ApiService().addDoctorInfo(data: {
      "userId": userId,
      "hospitalNo": hospId,
      "doctorType": doType,
      "doctorNick": "jj",
      "dept01": depParent,
      "dept02": deptChild,
      "title": title,
      "duty": duty
    });
    if (httpData.code == 1) {
      nextStep();
    } else {
      ToastUtils.toast("提交医生信息失败");
    }
  }

  /// 提价资质认证证书
  void addDrAuthInfo() async {
    String goodAt = fieldController.text;
    String perProfile = personalController.text;
    String prac1 = imgPathPrac1.value;
    String prac2 = imgPathPrac1.value;
    String certTitle1 = imgPathTitle1.value;
    String certTitle2 = imgPathTitle2.value;
    String xpPath = imgPathXp.value;
    if (prac1.isEmpty ||
        prac2.isEmpty ||
        certTitle1.isEmpty ||
        certTitle2.isEmpty ||
        xpPath.isEmpty) {
      ToastUtils.toast("请上传您的证书进行认证");
      return;
    }

    HttpData httpData = await ApiService().addDoctorInfo(data: {
      "userId": userId,
      "beGoodAt": goodAt,
      "personalProfile": perProfile,
      "certLicenseMain": prac1,
      "certLicenseSub": prac2,
      "certTitleMain": certTitle1,
      "certTitleSub": certTitle2,
      "breastpiece": xpPath,
    });
    if (httpData.code == 1) {
      Get.toNamed(AppRoutes.datareview);
    } else {
      ToastUtils.toast("提交资质认证失败");
    }
  }

  /// 身份证信息校验
  void validId() async {
    String realName = nameController.text;
    String idCard = idCardController.text;
    if (realName.isEmpty || idCard.isEmpty) {
      ToastUtils.toast("实名信息不能为空");
      return;
    }
    Map<String, dynamic> res = await ApiService().validIDCardInfo(
        data: {"name": realName, "idcard": idCard},
        options: Options(
          headers: {
            "Authorization": "APPCODE 9e325926776f45b5ad7304181a374e88",
            Headers.acceptHeader: {"accept: application/json"}
          },
        ));
    IdcardValidData cardData = IdcardValidData.fromJson(res);
    if (cardData.code == '0' && cardData.result!.res == '1') {
      sex.value = cardData.result!.sex == '女' ? "0" : "1";
      address.value = cardData.result!.address!;
      String bvalue = cardData.result!.birthday!;
      int year = int.parse(bvalue.substring(0, 4));
      int month = int.parse(bvalue.substring(4, 6));
      int day = int.parse(bvalue.substring(7, bvalue.length));
      String dateTime = TimeTool.strToDate(bvalue);
      // formatDate(DateTime(year, month, day), [yyyy, '-', m, '-', d]);

      birthday.value = dateTime!;
      ToastUtils.toast("身份验证成功");
    } else {
      ToastUtils.toast('身份验证失败');
    }
  }
}
